<!DOCTYPE html>




<html class="theme-next mist" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="MongoDB," />








  <link rel="shortcut icon" type="image/x-icon" href="/images/favicon-16x16-next.png?v=5.1.2" />






<meta name="description" content="MongoDB 教程举例说明   id user_name email age city     1 Mark Hanks mark@abc.com 25 Los Angeles   2 Richard Peter richard@abc.com 31 Dallas    {“_id”: ObjectId(“5146bb52d8524270060001f3”),“age”:25,“city”:”L">
<meta name="keywords" content="MongoDB">
<meta property="og:type" content="article">
<meta property="og:title" content="MongoDB由浅入深">
<meta property="og:url" content="http://xchcloud.cn/MongoDB由浅入深/index.html">
<meta property="og:site_name" content="超哥记录日记">
<meta property="og:description" content="MongoDB 教程举例说明   id user_name email age city     1 Mark Hanks mark@abc.com 25 Los Angeles   2 Richard Peter richard@abc.com 31 Dallas    {“_id”: ObjectId(“5146bb52d8524270060001f3”),“age”:25,“city”:”L">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-12-02T13:18:42.347Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="MongoDB由浅入深">
<meta name="twitter:description" content="MongoDB 教程举例说明   id user_name email age city     1 Mark Hanks mark@abc.com 25 Los Angeles   2 Richard Peter richard@abc.com 31 Dallas    {“_id”: ObjectId(“5146bb52d8524270060001f3”),“age”:25,“city”:”L">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"always","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://xchcloud.cn/MongoDB由浅入深/"/>





  <title>MongoDB由浅入深 | 超哥记录日记</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b8d23512908ca3b4b175b2620a75740f";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">超哥记录日记</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">生命有息、学无止境、折腾不止</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://xchcloud.cn/MongoDB由浅入深/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="John Doe">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://tuchuang-xchcloud-1253428588.cos.ap-chengdu.myqcloud.com/blog/header.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="超哥记录日记">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">MongoDB由浅入深</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-12-01T12:30:10+08:00">
                2018-12-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/MongoDB/" itemprop="url" rel="index">
                    <span itemprop="name">MongoDB</span>
                  </a>
                </span>

                
                
              
            </span>
          

 


          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o">访问数</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>°C
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计</span>
                
                <span title="字数统计">
                  3,669
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长</span>
                
                <span title="阅读时长">
                  15
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="MongoDB-教程"><a href="#MongoDB-教程" class="headerlink" title="MongoDB 教程"></a><a href="http://www.runoob.com/mongodb/mongodb-tutorial.html" target="_blank" rel="noopener">MongoDB 教程</a></h2><h3 id="举例说明"><a href="#举例说明" class="headerlink" title="举例说明"></a>举例说明</h3><table>
<thead>
<tr>
<th>id</th>
<th>user_name</th>
<th>email</th>
<th>age</th>
<th>city</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Mark Hanks</td>
<td><a href="mailto:mark@abc.com" target="_blank" rel="noopener">mark@abc.com</a></td>
<td>25</td>
<td>Los Angeles</td>
</tr>
<tr>
<td>2</td>
<td>Richard Peter</td>
<td><a href="mailto:richard@abc.com" target="_blank" rel="noopener">richard@abc.com</a></td>
<td>31</td>
<td>Dallas</td>
</tr>
</tbody>
</table>
<p>{<br>“_id”: ObjectId(“5146bb52d8524270060001f3”),<br>“age”:25,<br>“city”:”Los Angele3”,<br>“email”:”mark@ abc. com”,<br>“user_name”:”Mark Hanka”<br>}<br>{<br>“_id”: ObjectId(“5146bb52d8524270060001f2”),<br>“age”:31,<br>“city”:”Dallas”,<br>“email”:”richardeabc. com”,<br>“user name”:”Richard Peter”<br>}</p>
<h3 id="MongoDB-与-RDBMS-术语的比较："><a href="#MongoDB-与-RDBMS-术语的比较：" class="headerlink" title="MongoDB 与 RDBMS 术语的比较："></a>MongoDB 与 RDBMS 术语的比较：</h3><table>
<thead>
<tr>
<th>SQL术语/概念</th>
<th>MongoDB术语/概念</th>
<th>解释/说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>database</td>
<td>database</td>
<td>数据库</td>
</tr>
<tr>
<td>table</td>
<td>collection</td>
<td>数据库表/集合</td>
</tr>
<tr>
<td>row</td>
<td>document</td>
<td>数据记录行/文档</td>
</tr>
<tr>
<td>column</td>
<td>field</td>
<td>数据字段/域</td>
</tr>
<tr>
<td>index</td>
<td>index</td>
<td>索引</td>
</tr>
<tr>
<td>table joins</td>
<td></td>
<td>表连接,MongoDB不支持</td>
</tr>
<tr>
<td>primary key</td>
<td>primary key</td>
<td>主键,MongoDB自动将_id字段设置为主键</td>
</tr>
</tbody>
</table>
<h3 id="MongoDB-与-RDBMS-Where-语句比较"><a href="#MongoDB-与-RDBMS-Where-语句比较" class="headerlink" title="MongoDB 与 RDBMS Where 语句比较"></a>MongoDB 与 RDBMS Where 语句比较</h3><table>
<thead>
<tr>
<th>操作</th>
<th>格式</th>
<th>范例</th>
<th>RDBMS中的类似语句</th>
</tr>
</thead>
<tbody>
<tr>
<td>等于</td>
<td>{<key>:<value>}</value></key></td>
<td>db.col.find({“by”:”XCHCOUD”}).pretty()</td>
<td>where by = ‘XCHCOUD’</td>
</tr>
<tr>
<td>小于</td>
<td>{<key>:{$lt:<value>}}</value></key></td>
<td>db.col.find({“likes”:{$lt:50}}).pretty()</td>
<td>where likes &lt; 50</td>
</tr>
<tr>
<td>小于或等于</td>
<td>{<key>:{$lte:<value>}}</value></key></td>
<td>db.col.find({“likes”:{$lte:50}}).pretty()</td>
<td>where likes &lt;= 50</td>
</tr>
<tr>
<td>大于</td>
<td>{<key>:{$gt:<value>}}</value></key></td>
<td>db.col.find({“likes”:{$gt:50}}).pretty()</td>
<td>where likes &gt; 50</td>
</tr>
<tr>
<td>大于或等于</td>
<td>{<key>:{$gte:<value>}}</value></key></td>
<td>db.col.find({“likes”:{$gte:50}}).pretty()</td>
<td>where likes &gt;= 50</td>
</tr>
<tr>
<td>不等于</td>
<td>{<key>:{$ne:<value>}}</value></key></td>
<td>db.col.find({“likes”:{$ne:50}}).pretty()</td>
<td>where likes != 50</td>
</tr>
</tbody>
</table>
<h3 id="MongoDB-AND-条件"><a href="#MongoDB-AND-条件" class="headerlink" title="MongoDB AND 条件"></a>MongoDB AND 条件</h3><p><code>db.col.find({key1:value1, key2:value2}).pretty()</code></p>
<h3 id="MongoDB-OR-条件"><a href="#MongoDB-OR-条件" class="headerlink" title="MongoDB OR 条件"></a>MongoDB OR 条件</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">   &#123;</span><br><span class="line">      $or: [</span><br><span class="line">         &#123;key1: value1&#125;, &#123;key2:value2&#125;</span><br><span class="line">      ]</span><br><span class="line">   &#125;</span><br><span class="line">).pretty()</span><br></pre></td></tr></table></figure>
<h3 id="AND-和-OR-联合使用"><a href="#AND-和-OR-联合使用" class="headerlink" title="AND 和 OR 联合使用"></a>AND 和 OR 联合使用</h3><p><em>SQL:</em></p>
<p><code>where likes&gt;50 AND (by = &#39;菜鸟教程&#39; OR title = &#39;MongoDB 教程&#39;)</code></p>
<p><em>MongoDB:</em></p>
<figure class="highlight plain"><figcaption><span>&#123;$gt:50&#125;, $or: [&#123;"by": "XCHCLOUD"&#125;,&#123;"title": "MongoDB 教程"&#125;]&#125;).pretty()</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">        &quot;_id&quot; : ObjectId(&quot;56063f17ade2f21f36b03133&quot;),</span><br><span class="line">        &quot;title&quot; : &quot;MongoDB 教程&quot;,</span><br><span class="line">        &quot;description&quot; : &quot;MongoDB 是一个 Nosql 数据库&quot;,</span><br><span class="line">        &quot;by&quot; : &quot;XCHCLOUD&quot;,</span><br><span class="line">        &quot;url&quot; : &quot;http://XCHCLOUD.cn&quot;,</span><br><span class="line">        &quot;tags&quot; : [</span><br><span class="line">                &quot;mongodb&quot;,</span><br><span class="line">                &quot;database&quot;,</span><br><span class="line">                &quot;NoSQL&quot;</span><br><span class="line">        ],</span><br><span class="line">        &quot;likes&quot; : 100</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="条件操作符"><a href="#条件操作符" class="headerlink" title="条件操作符"></a>条件操作符</h3><table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th>MongoDB</th>
<th>Mysql</th>
</tr>
</thead>
<tbody>
<tr>
<td>&gt;</td>
<td>大于</td>
<td>$gt</td>
<td>db.col.find({likes : {$gt : 100}})</td>
<td>Select * from col where likes &gt; 100;</td>
</tr>
<tr>
<td>&lt;</td>
<td>小于</td>
<td>$lt</td>
<td>db.col.find({likes : {$lt : 150}})</td>
<td>Select * from col where likes &lt; 150;</td>
</tr>
<tr>
<td>&gt;=</td>
<td>大于等于</td>
<td>$gte</td>
<td>db.col.find({likes : {$gte : 100}})</td>
<td>Select * from col where likes &gt;=100;</td>
</tr>
<tr>
<td>&lt;=</td>
<td>小于等于</td>
<td>$lte</td>
<td>db.col.find({likes : {$lte : 150}})</td>
<td>Select * from col where likes &lt;= 150;</td>
</tr>
<tr>
<td>&gt;和&lt;</td>
<td>小于大于</td>
<td>$lt 和 $gt</td>
<td>db.col.find({likes : {$lt :200, $gt : 100}})</td>
<td>Select * from col where likes&gt;100 AND  likes&lt;200;</td>
</tr>
</tbody>
</table>
<h3 id="type-操作符"><a href="#type-操作符" class="headerlink" title="$type 操作符"></a>$type 操作符</h3><p>$type 操作符是基于 BSON 类型来检索集合中匹配的数据类型，并返回结果。</p>
<table>
<thead>
<tr>
<th>类型</th>
<th>数字</th>
<th>备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>Double</td>
<td>1</td>
<td></td>
</tr>
<tr>
<td>String</td>
<td>2</td>
<td></td>
</tr>
<tr>
<td>Object</td>
<td>3</td>
<td></td>
</tr>
<tr>
<td>Array</td>
<td>4</td>
<td></td>
</tr>
<tr>
<td>Binary data</td>
<td>5</td>
<td></td>
</tr>
<tr>
<td>Undefined</td>
<td>6</td>
<td>已废弃。</td>
</tr>
<tr>
<td>Object id</td>
<td>7</td>
<td></td>
</tr>
<tr>
<td>Boolean</td>
<td>8</td>
<td></td>
</tr>
<tr>
<td>Date</td>
<td>9</td>
<td></td>
</tr>
<tr>
<td>Null</td>
<td>10</td>
<td></td>
</tr>
<tr>
<td>Regular Expression</td>
<td>11</td>
<td></td>
</tr>
<tr>
<td>JavaScript</td>
<td>13</td>
<td></td>
</tr>
<tr>
<td>Symbol</td>
<td>14</td>
<td></td>
</tr>
<tr>
<td>JavaScript (with scope)</td>
<td>15</td>
<td></td>
</tr>
<tr>
<td>32-bit integer</td>
<td>16</td>
<td></td>
</tr>
<tr>
<td>Timestamp</td>
<td>17</td>
<td></td>
</tr>
<tr>
<td>64-bit integer</td>
<td>18</td>
<td></td>
</tr>
<tr>
<td>Min key</td>
<td>255</td>
<td>Query with -1.</td>
</tr>
<tr>
<td>Max key</td>
<td>127</td>
</tr>
</tbody>
</table>
<h3 id="Limit与Skip方法"><a href="#Limit与Skip方法" class="headerlink" title="Limit与Skip方法"></a>Limit与Skip方法</h3><h4 id="Limit-方法"><a href="#Limit-方法" class="headerlink" title="Limit() 方法"></a>Limit() 方法</h4><p>limit()方法在MongoDB中读取指定数量的数据记录，该参数指定从MongoDB中读取的记录条数。</p>
<p><code>db.COLLECTION_NAME.find().limit(NUMBER)</code></p>
<h4 id="Skip-方法"><a href="#Skip-方法" class="headerlink" title="Skip() 方法"></a>Skip() 方法</h4><p>skip()方法来跳过指定数量的数据，skip方法同样接受一个数字参数作为跳过的记录条数。</p>
<p><code>db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER)</code></p>
<h2 id="集合"><a href="#集合" class="headerlink" title="集合"></a>集合</h2><p>集合存在于数据库中，集合没有固定的结构，这意味着你在对集合可以插入不同格式和类型的数据，但通常情况下我们插入集合的数据都会有一定的关联性。</p>
<h3 id="创建集合"><a href="#创建集合" class="headerlink" title="创建集合"></a>创建集合</h3><p><code>db.createCollection(name, options)</code></p>
<p><strong>参数说明：</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>name</td>
<td>要创建的集合名称</td>
</tr>
<tr>
<td>options</td>
<td>可选参数, 指定有关内存大小及索引的选项</td>
</tr>
</tbody>
</table>
<p><strong>options参数：</strong><br>| 字段            | 类型     | 描述                                                                                                                                                    |<br>|————-    |——    |—————————————————————————————————————————————————–    |<br>| capped          | 布尔     | （可选）如果为 true，则创建固定集合。固定集合是指有着固定大小的集合，当达到最大值时，它会自动覆盖最早的文档。当该值为 true 时，必须指定 size 参数。     |<br>| autoIndexId     | 布尔     | （可选）如为 true，自动在 _id 字段创建索引。默认为 false。                                                                                              |<br>| size            | 数值     | （可选）为固定集合指定一个最大值（以字节计）。如果 capped 为 true，也需要指定该字段。                                                                   |<br>| max             | 数值     | （可选）指定固定集合中包含文档的最大数量。                                                                                                              |</p>
<h3 id="删除集合"><a href="#删除集合" class="headerlink" title="删除集合"></a>删除集合</h3><p><code>db.collection.drop()</code></p>
<h2 id="文档"><a href="#文档" class="headerlink" title="文档"></a>文档</h2><h3 id="插入文档"><a href="#插入文档" class="headerlink" title="插入文档"></a>插入文档</h3><p><code>db.COLLECTION_NAME.insert(document)</code></p>
<p>可以将数据定义为变量形式</p>
<p><code>db.col.insert(document)</code></p>
<h3 id="查看已插入文档"><a href="#查看已插入文档" class="headerlink" title="查看已插入文档"></a>查看已插入文档</h3><p><code>db.col.find()</code></p>
<h3 id="更新文档"><a href="#更新文档" class="headerlink" title="更新文档"></a>更新文档</h3><h4 id="update-方法"><a href="#update-方法" class="headerlink" title="update() 方法"></a>update() 方法</h4><p>update() 方法用于更新已存在的文档。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">   &lt;query&gt;,</span><br><span class="line">   &lt;update&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     upsert: &lt;boolean&gt;,</span><br><span class="line">     multi: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><strong>参数说明：</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>query</td>
<td>update的查询条件，类似sql update查询内where后面的。</td>
</tr>
<tr>
<td>update</td>
<td>update的对象和一些更新的操作符（如$,$inc…）等，也可以理解为sql update查询内set后面的</td>
</tr>
<tr>
<td>upsert</td>
<td>可选，这个参数的意思是，如果不存在update的记录，是否插入objNew,true为插入，默认是false，不插入。</td>
</tr>
<tr>
<td>multi</td>
<td><strong>可选，mongodb 默认是false,只更新找到的第一条记录，如果这个参数为true,就把按条件查出来多条记录全部更新。</strong></td>
</tr>
<tr>
<td>writeConcern</td>
<td>可选，抛出异常的级别。</td>
</tr>
</tbody>
</table>
<h4 id="save-方法"><a href="#save-方法" class="headerlink" title="save() 方法"></a>save() 方法</h4><p>save() 方法通过传入的文档来替换已有文档。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">   &lt;document&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><strong>参数说明：</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>document</td>
<td>文档数据。</td>
</tr>
<tr>
<td>writeConcern</td>
<td>可选，抛出异常的级别。</td>
</tr>
</tbody>
</table>
<h4 id="删除文档"><a href="#删除文档" class="headerlink" title="删除文档"></a>删除文档</h4><p><del>2.6 版本以前的</del></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">   &lt;query&gt;,</span><br><span class="line">   &lt;justOne&gt;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><em>2.6版本以后的</em></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">   &lt;query&gt;,</span><br><span class="line">   &#123;</span><br><span class="line">     justOne: &lt;boolean&gt;,</span><br><span class="line">     writeConcern: &lt;document&gt;</span><br><span class="line">   &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p><strong>参数说明：</strong><br>| 参数             | 说明                                                                                                               |<br>|————–    |—————————————————————————————————————-    |<br>| query            | （可选）删除的文档的条件。                                                                                         |<br>| justOne          | （可选）如果设为 true 或 1，则只删除一个文档，如果不设置该参数，或使用默认值 false，则删除所有匹配条件的文档。     |<br>| writeConcern     | （可选）抛出异常的级别。                                                                                           |</p>
<h3 id="查询文档"><a href="#查询文档" class="headerlink" title="查询文档"></a>查询文档</h3><p><code>db.collection.find(query, projection).pretty()</code></p>
<p><em>除了 find() 方法之外，还有一个 findOne() 方法，它只返回一个文档。</em></p>
<p><strong>参数说明：</strong></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>query</td>
<td>可选，使用查询操作符指定查询条件</td>
</tr>
<tr>
<td>projection</td>
<td>可选，使用投影操作符指定返回的键。查询时返回文档中所有键值， 只需省略该参数即可（默认省略）。如果你需要以易读的方式来读取数据，可以使用 pretty() 方法，语法格式如下：</td>
</tr>
<tr>
<td>.pretty()</td>
<td>pretty() 方法以格式化的方式来显示所有文档</td>
</tr>
</tbody>
</table>
<h2 id="元数据"><a href="#元数据" class="headerlink" title="元数据"></a>元数据</h2><h2 id="Obiectld"><a href="#Obiectld" class="headerlink" title="Obiectld"></a>Obiectld</h2><p>ObjectId 类似唯一主键，可以很快的去生成和排序，包含 12 bytes，含义是：</p>
<table>
<thead>
<tr>
<th>0、1、2、3</th>
<th>4、5、6</th>
<th>7、8</th>
<th>9、10、11</th>
</tr>
</thead>
<tbody>
<tr>
<td>时间戳</td>
<td>机器</td>
<td>pID</td>
<td>计数器</td>
</tr>
</tbody>
</table>
<p>MongoDB 中存储的文档必须有一个 _id 键。这个键的值可以是任何类型的，默认是个 ObjectId 对象</p>
<h2 id="排序"><a href="#排序" class="headerlink" title="排序"></a>排序</h2><p>使用 sort() 方法对数据进行排序，sort() 方法可以通过参数指定排序的字段，并使用 1 和 -1 来指定排序的方式，其中 1 为升序排列，而 -1 是用于降序排列。</p>
<p><code>db.COLLECTION_NAME.find().sort({KEY:1})</code></p>
<h2 id="索引"><a href="#索引" class="headerlink" title="索引"></a>索引</h2><h3 id="createIndex-方法"><a href="#createIndex-方法" class="headerlink" title="createIndex() 方法"></a>createIndex() 方法</h3><p><code>db.collection.createIndex(keys, options)</code><br>语法中 Key 值为你要创建的索引字段，1 为指定按升序创建索引，-1 为指定按降序创建索引；createIndex() 方法中你也可以设置使用多个字段创建索引。</p>
<p>可选参数</p>
<table>
<thead>
<tr>
<th>Parameter</th>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>background</td>
<td>Boolean</td>
<td>建索引过程会阻塞其它数据库操作，background可指定以后台方式创建索引，即增加 “background” 可选参数。 “background” 默认值为false。</td>
</tr>
<tr>
<td>unique</td>
<td>Boolean</td>
<td>建立的索引是否唯一。指定为true创建唯一索引。默认值为false.</td>
</tr>
<tr>
<td>name</td>
<td>string</td>
<td>索引的名称。如果未指定，MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。</td>
</tr>
<tr>
<td>dropDups</td>
<td>Boolean</td>
<td>3.0+版本已废弃。在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false.</td>
</tr>
<tr>
<td>sparse</td>
<td>Boolean</td>
<td>对文档中不存在的字段数据不启用索引；这个参数需要特别注意，如果设置为true的话，在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.</td>
</tr>
<tr>
<td>expireAfterSeconds</td>
<td>integer</td>
<td>指定一个以秒为单位的数值，完成 TTL设定，设定集合的生存时间。</td>
</tr>
<tr>
<td>v</td>
<td>index version</td>
<td>索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。</td>
</tr>
<tr>
<td>weights</td>
<td>document</td>
<td>索引权重值，数值在 1 到 99,999 之间，表示该索引相对于其他索引字段的得分权重。</td>
</tr>
<tr>
<td>default_language</td>
<td>string</td>
<td>对于文本索引，该参数决定了停用词及词干和词器的规则的列表。 默认为英语</td>
</tr>
<tr>
<td>language_override</td>
<td>string</td>
<td>对于文本索引，该参数指定了包含在文档中的字段名，语言覆盖默认的language，默认值为 language.</td>
</tr>
</tbody>
</table>
<h2 id="聚合"><a href="#聚合" class="headerlink" title="聚合"></a>聚合</h2><p>主要用于处理数据(诸如统计平均值,求和等)，并返回计算后的数据结果。有点类似sql语句中的 count(*)。</p>
<h3 id="aggregate-方法"><a href="#aggregate-方法" class="headerlink" title="aggregate() 方法"></a>aggregate() 方法</h3><p><code>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)</code></p>
<p><strong>比较mysql</strong></p>
<p><code>select by_user, count(*) from mycol group by by_user</code></p>
<h3 id="聚合的表达式"><a href="#聚合的表达式" class="headerlink" title="聚合的表达式"></a>聚合的表达式</h3><table>
<thead>
<tr>
<th>表达式</th>
<th>描述</th>
<th>实例</th>
</tr>
</thead>
<tbody>
<tr>
<td>$sum</td>
<td>计算总和。</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$sum : “$likes”}}}])</td>
</tr>
<tr>
<td>$avg</td>
<td>计算平均值</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$avg : “$likes”}}}])</td>
</tr>
<tr>
<td>$min</td>
<td>获取集合中所有文档对应值得最小值。</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$min : “$likes”}}}])</td>
</tr>
<tr>
<td>$max</td>
<td>获取集合中所有文档对应值得最大值。</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$max : “$likes”}}}])</td>
</tr>
<tr>
<td>$push</td>
<td>在结果文档中插入值到一个数组中。</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$push: “$url”}}}])</td>
</tr>
<tr>
<td>$addToSet</td>
<td>在结果文档中插入值到一个数组中，但不创建副本。</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$addToSet : “$url”}}}])</td>
</tr>
<tr>
<td>$first</td>
<td>根据资源文档的排序获取第一个文档数据。</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, first_url : {$first : “$url”}}}])</td>
</tr>
<tr>
<td>$last</td>
<td>根据资源文档的排序获取最后一个文档数据</td>
<td>db.mycol.aggregate([{$group : {_id : “$by_user”, last_url : {$last : “$url”}}}])</td>
</tr>
</tbody>
</table>
<h3 id="管道"><a href="#管道" class="headerlink" title="管道"></a>管道</h3><p>管道在Unix和Linux中一般用于将当前命令的输出结果作为下一个命令的参数。MongoDB的聚合管道将MongoDB文档在一个管道处理完毕后将结果传递给下一个管道处理。管道操作是可以重复的。</p>
<p><strong>参数</strong></p>
<table>
<thead>
<tr>
<th>$project</th>
<th>修改输入文档的结构。可以用来重命名、增加或删除域，也可以用于创建计算结果以及嵌套文档。</th>
</tr>
</thead>
<tbody>
<tr>
<td>$match</td>
<td>用于过滤数据，只输出符合条件的文档。$match使用MongoDB的标准查询操作。</td>
</tr>
<tr>
<td>$limit</td>
<td>用来限制MongoDB聚合管道返回的文档数。</td>
</tr>
<tr>
<td>$skip</td>
<td>在聚合管道中跳过指定数量的文档，并返回余下的文档。</td>
</tr>
<tr>
<td>$unwind</td>
<td>将文档中的某一个数组类型字段拆分成多条，每条包含数组中的一个值。</td>
</tr>
<tr>
<td>$group</td>
<td>将集合中的文档分组，可用于统计结果。</td>
</tr>
<tr>
<td>$sortr</td>
<td>输出接近某一地理位置的有序文档。</td>
</tr>
</tbody>
</table>
<h2 id="备份-mongodump-与恢复-mongorestore"><a href="#备份-mongodump-与恢复-mongorestore" class="headerlink" title="备份(mongodump)与恢复(mongorestore)"></a>备份(mongodump)与恢复(mongorestore)</h2><h3 id="数据备份"><a href="#数据备份" class="headerlink" title="数据备份"></a>数据备份</h3><p>导出所有数据到指定目录中</p>
<p><code>mongodump -h dbhost -d dbname -o dbdirectory</code></p>
<p><strong>参数：</strong></p>
<table>
<thead>
<tr>
<th>h</th>
<th>MongDB所在服务器地址，例如：127.0.0.1，当然也可以指定端口号：127.0.0.1:27017</th>
</tr>
</thead>
<tbody>
<tr>
<td>d</td>
<td>需要备份的数据库实例，例如：test</td>
</tr>
<tr>
<td>o</td>
<td>备份的数据存放位置，例如：c:\data\dump，当然该目录需要提前建立，在备份完成后，系统自动在dump目录下建立一个test目录，这个目录里面存放该数据库实例的备份数据。</td>
</tr>
</tbody>
</table>
<h3 id="数据恢复"><a href="#数据恢复" class="headerlink" title="数据恢复"></a>数据恢复</h3><p><code>mongorestore -h &lt;hostname&gt;&lt;:port&gt; -d dbname &lt;path&gt;</code></p>
<p><strong>参数：</strong></p>
<table>
<thead>
<tr>
<th>–host &lt;:port&gt;, -h &lt;:port&gt;</th>
<th>MongoDB所在服务器地址，默认为： localhost:27017</th>
</tr>
</thead>
<tbody>
<tr>
<td>–db , -d</td>
<td>需要恢复的数据库实例，例如：test，当然这个名称也可以和备份时候的不一样，比如test2</td>
</tr>
<tr>
<td>–drop</td>
<td>恢复的时候，先删除当前数据，然后恢复备份的数据。就是说，恢复后，备份后添加修改的数据都会被删除，慎用哦！</td>
</tr>
<tr>
<td><path></path></td>
<td>mongorestore 最后的一个参数，设置备份数据所在位置，例如：c:\data\dump\test。你不能同时指定 <path></path> 和 –dir 选项，–dir也可以设置备份目录。</td>
</tr>
<tr>
<td>–dir</td>
<td>指定备份的目录。你不能同时指定 <path></path> 和 –dir 选项</td>
</tr>
</tbody>
</table>
<h2 id="监控"><a href="#监控" class="headerlink" title="监控"></a>监控</h2><h3 id="mongostat-命令"><a href="#mongostat-命令" class="headerlink" title="mongostat 命令"></a>mongostat 命令</h3><p>它会间隔固定时间获取mongodb的当前运行状态，并输出。</p>
<h3 id="mongotop-命令"><a href="#mongotop-命令" class="headerlink" title="mongotop 命令"></a>mongotop 命令</h3><p>用来跟踪一个MongoDB的实例，查看哪些大量的时间花费在读取和写入数据。mongotop提供每个集合的水平的统计数据。默认情况下，mongotop返回值的每一秒。</p>
<p><code>mongotop &lt;sleeptime&gt;</code></p>
<p><strong>参数：</strong></p>
<p>等待的时间长度，以秒为单位，mongotop等待调用之间。通过的默认mongotop返回数据的每一秒。</p>
<p><strong><code>mongotop --locks</code></strong></p>
<p><strong>返回参数说明</strong></p>
<table>
<thead>
<tr>
<th>ns</th>
<th>包含数据库命名空间，后者结合了数据库名称和集合。</th>
</tr>
</thead>
<tbody>
<tr>
<td>db</td>
<td>包含数据库的名称。名为 . 的数据库针对全局锁定，而非特定数据库。</td>
</tr>
<tr>
<td>total</td>
<td>mongod花费的时间工作在这个命名空间提供总额。</td>
</tr>
<tr>
<td>read</td>
<td>提供了大量的时间，这mongod花费在执行读操作，在此命名空间。</td>
</tr>
<tr>
<td>write</td>
<td>提供这个命名空间进行写操作，这mongod花了大量的时间。</td>
</tr>
</tbody>
</table>
<h2 id="查询分析"><a href="#查询分析" class="headerlink" title="查询分析"></a>查询分析</h2><p>可以确保我们建议的索引是否有效，是查询语句性能分析的重要工具。</p>
<h3 id="explain"><a href="#explain" class="headerlink" title="explain()"></a>explain()</h3><p>提供了查询信息，使用索引及查询统计等。</p>
<p>创建 gender 和 user_name 的索引：<br><code>db.users.ensureIndex({gender:1,user_name:1})</code><br>现在在查询语句中使用 explain ：<br><code>&gt;db.users.find({gender:&quot;M&quot;},{user_name:1,_id:0}).explain()</code></p>
<p><strong>返回结果参数说明</strong></p>
<table>
<thead>
<tr>
<th>indexOnly</th>
<th>字段为 true ，表示我们使用了索引。</th>
</tr>
</thead>
<tbody>
<tr>
<td>cursor</td>
<td>因为这个查询使用了索引，MongoDB 中索引存储在B树结构中，所以这是也使用了 BtreeCursor 类型的游标。如果没有使用索引，游标的类型是 BasicCursor。这个键还会给出你所使用的索引的名称，你通过这个名称可以查看当前数据库下的system.indexes集合（系统自动创建，由于存储索引信息，这个稍微会提到）来得到索引的详细信息。</td>
</tr>
<tr>
<td>n</td>
<td>当前查询返回的文档数量。</td>
</tr>
<tr>
<td>nscanned/nscannedObjects</td>
<td>表明当前这次查询一共扫描了集合中多少个文档，我们的目的是，让这个数值和返回文档的数量越接近越好。</td>
</tr>
<tr>
<td>millis</td>
<td>当前查询所需时间，毫秒数。</td>
</tr>
<tr>
<td>indexBounds</td>
<td>当前查询具体使用的索引。</td>
</tr>
</tbody>
</table>
<h3 id="hint"><a href="#hint" class="headerlink" title="hint()"></a>hint()</h3><p>使用 hint 来强制 MongoDB 使用一个指定的索引。</p>
<p>指定了使用 gender 和 user_name 索引字段来查询：<br><code>&gt;db.users.find({gender:&quot;M&quot;},{user_name:1,_id:0}).hint({gender:1,user_name:1})</code><br>可以使用 explain() 函数来分析以上查询：<br><code>&gt;db.users.find({gender:&quot;M&quot;},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain()</code></p>
<h2 id="原子操作常用命令"><a href="#原子操作常用命令" class="headerlink" title="原子操作常用命令"></a>原子操作常用命令</h2><table>
<thead>
<tr>
<th>$set</th>
<th>用来指定一个键并更新键值，若键不存在并创建。</th>
<th>{ $set : { field : value } }</th>
</tr>
</thead>
<tbody>
<tr>
<td>$unset</td>
<td>用来删除一个键。</td>
<td>{ $unset : { field : 1} }</td>
</tr>
<tr>
<td>$inc</td>
<td>$inc可以对文档的某个值为数字型（只能为满足要求的数字）的键进行增减的操作。</td>
<td>{ $inc : { field : value } }</td>
</tr>
<tr>
<td>$push</td>
<td>把value追加到field里面去，field一定要是数组类型才行，如果field不存在，会新增一个数组类型加进去。</td>
<td>{ $push : { field : value } }</td>
</tr>
<tr>
<td>$pushAll</td>
<td>同$push,只是一次可以追加多个值到一个数组字段内。</td>
<td>{ $pushAll : { field : value_array } }</td>
</tr>
<tr>
<td>$pull</td>
<td>从数组field内删除一个等于value值。</td>
<td>{ $pull : { field : _value } }</td>
</tr>
<tr>
<td>$pop</td>
<td>删除数组的第一个或最后一个元素</td>
<td>{ $pop : { field : 1 } }</td>
</tr>
<tr>
<td>$rename</td>
<td>修改字段名称</td>
<td>{ $rename : { old_field_name : new_field_name } }</td>
</tr>
<tr>
<td>$bit</td>
<td>位操作，integer类型</td>
<td>{$bit : { field : {and : 5}}}</td>
</tr>
<tr>
<td>$addToSet</td>
<td>增加一个值到数组内，而且只有当这个值不在数组内才增加。</td>
<td></td>
</tr>
<tr>
<td></td>
<td>偏移操作符</td>
<td>t.find() { “_id” : ObjectId(“4b97e62bf1d8c7152c9ccb74”), “title” : “ABC”, “comments” : [ { “by” : “joe”, “votes” : 3 }, { “by” : “jane”, “votes” : 7 } ] }</td>
</tr>
</tbody>
</table>
<h2 id="MongoDB-Java"><a href="#MongoDB-Java" class="headerlink" title="MongoDB Java"></a>MongoDB Java</h2><p>下载mongo jar包，下载地址：<a href="http://mongodb.github.io/mongo-java-driver/" target="_blank" rel="noopener">http://mongodb.github.io/mongo-java-driver/</a>, 请确保下载最新版本。</p>
<p><a href="http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/" target="_blank" rel="noopener">http://mongodb.github.io/mongo-java-driver/3.0/driver/getting-started/quick-tour/</a></p>

      
    </div>
    
    
    

      <div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

  
</div>

<div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/MongoDB由浅入深/">MongoDB由浅入深</a></p>
  <p><span>文章作者:</span></a>Chao</p>
  <p><span>发布时间:</span>2018年12月01日 - 12:12</p>
  <p><span>最后更新:</span>2018年12月02日 - 21:12</p>
  <p><span>原始链接:</span><a href="/MongoDB由浅入深/" title="MongoDB由浅入深">http://xchcloud.cn/MongoDB由浅入深/</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://xchcloud.cn/MongoDB由浅入深/"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
      $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
        });
    });  
</script>

      
</div>

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/MongoDB/" <i class="fa fa-tag"></i> MongoDB</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/Mysql学习笔记/" rel="next" title="Mysql学习笔记">
                <i class="fa fa-chevron-left"></i> Mysql学习笔记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/新年新计划新起航/" rel="prev" title="新年新计划新起航">
                新年新计划新起航 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://tuchuang-xchcloud-1253428588.cos.ap-chengdu.myqcloud.com/blog/header.jpg"
               alt="John Doe" />
          </span></a>Chao</p>


           
              <p class="site-description motion-element" itemprop="description"></p>
           
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">60</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">33</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">65</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/lhc0101" target="_blank" title="Github">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                    
                      Github
                    
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=qJmcmp_akJ6ZmZHo2dmGy8fF" target="_blank" title="E-mail">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                    
                      E-mail
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              dalao&nbsp;
              <i class="fa  fa-fw fa-globe"></i>
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://giracle.cn" title="DJG" target="_blank">DJG</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://owencxc.github.io" title="CX" target="_blank">CX</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://www.myzwl.win" title="ZWL" target="_blank">ZWL</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://wuliekun.me/" title="WLK" target="_blank">WLK</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="https://Li-rr.github.io" title="LRR" target="_blank">LRR</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://dh.xchcloud.cn" title="导航" target="_blank">导航</a>
                </li>
              
            </ul>
+        <div id="days"></div>
</script>
<script language="javascript">
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("06/26/2018 12:00:00");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>

          </div>
         

-        <div id="days"></div>
</script>
<script language="javascript">
function show_date_time(){
window.setTimeout("show_date_time()", 1000);
BirthDay=new Date("06/26/2018 12:00:00");
today=new Date();
timeold=(today.getTime()-BirthDay.getTime());
sectimeold=timeold/1000
secondsold=Math.floor(sectimeold);
msPerDay=24*60*60*1000
e_daysold=timeold/msPerDay
daysold=Math.floor(e_daysold);
e_hrsold=(e_daysold-daysold)*24;
hrsold=setzero(Math.floor(e_hrsold));
e_minsold=(e_hrsold-hrsold)*60;
minsold=setzero(Math.floor((e_hrsold-hrsold)*60));
seconds=setzero(Math.floor((e_minsold-minsold)*60));
document.getElementById('days').innerHTML="已运行"+daysold+"天"+hrsold+"小时"+minsold+"分"+seconds+"秒";
}
function setzero(i){
if (i<10)
{i="0" + i};
return i;
}
show_date_time();
</script>


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB-教程"><span class="nav-number">1.</span> <span class="nav-text">MongoDB 教程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#举例说明"><span class="nav-number">1.1.</span> <span class="nav-text">举例说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB-与-RDBMS-术语的比较："><span class="nav-number">1.2.</span> <span class="nav-text">MongoDB 与 RDBMS 术语的比较：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB-与-RDBMS-Where-语句比较"><span class="nav-number">1.3.</span> <span class="nav-text">MongoDB 与 RDBMS Where 语句比较</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB-AND-条件"><span class="nav-number">1.4.</span> <span class="nav-text">MongoDB AND 条件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MongoDB-OR-条件"><span class="nav-number">1.5.</span> <span class="nav-text">MongoDB OR 条件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#AND-和-OR-联合使用"><span class="nav-number">1.6.</span> <span class="nav-text">AND 和 OR 联合使用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#条件操作符"><span class="nav-number">1.7.</span> <span class="nav-text">条件操作符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#type-操作符"><span class="nav-number">1.8.</span> <span class="nav-text">$type 操作符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Limit与Skip方法"><span class="nav-number">1.9.</span> <span class="nav-text">Limit与Skip方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Limit-方法"><span class="nav-number">1.9.1.</span> <span class="nav-text">Limit() 方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Skip-方法"><span class="nav-number">1.9.2.</span> <span class="nav-text">Skip() 方法</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#集合"><span class="nav-number">2.</span> <span class="nav-text">集合</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建集合"><span class="nav-number">2.1.</span> <span class="nav-text">创建集合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除集合"><span class="nav-number">2.2.</span> <span class="nav-text">删除集合</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文档"><span class="nav-number">3.</span> <span class="nav-text">文档</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#插入文档"><span class="nav-number">3.1.</span> <span class="nav-text">插入文档</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查看已插入文档"><span class="nav-number">3.2.</span> <span class="nav-text">查看已插入文档</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#更新文档"><span class="nav-number">3.3.</span> <span class="nav-text">更新文档</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#update-方法"><span class="nav-number">3.3.1.</span> <span class="nav-text">update() 方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#save-方法"><span class="nav-number">3.3.2.</span> <span class="nav-text">save() 方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#删除文档"><span class="nav-number">3.3.3.</span> <span class="nav-text">删除文档</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查询文档"><span class="nav-number">3.4.</span> <span class="nav-text">查询文档</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#元数据"><span class="nav-number">4.</span> <span class="nav-text">元数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Obiectld"><span class="nav-number">5.</span> <span class="nav-text">Obiectld</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#排序"><span class="nav-number">6.</span> <span class="nav-text">排序</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#索引"><span class="nav-number">7.</span> <span class="nav-text">索引</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#createIndex-方法"><span class="nav-number">7.1.</span> <span class="nav-text">createIndex() 方法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#聚合"><span class="nav-number">8.</span> <span class="nav-text">聚合</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#aggregate-方法"><span class="nav-number">8.1.</span> <span class="nav-text">aggregate() 方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#聚合的表达式"><span class="nav-number">8.2.</span> <span class="nav-text">聚合的表达式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#管道"><span class="nav-number">8.3.</span> <span class="nav-text">管道</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#备份-mongodump-与恢复-mongorestore"><span class="nav-number">9.</span> <span class="nav-text">备份(mongodump)与恢复(mongorestore)</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数据备份"><span class="nav-number">9.1.</span> <span class="nav-text">数据备份</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据恢复"><span class="nav-number">9.2.</span> <span class="nav-text">数据恢复</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#监控"><span class="nav-number">10.</span> <span class="nav-text">监控</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#mongostat-命令"><span class="nav-number">10.1.</span> <span class="nav-text">mongostat 命令</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#mongotop-命令"><span class="nav-number">10.2.</span> <span class="nav-text">mongotop 命令</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#查询分析"><span class="nav-number">11.</span> <span class="nav-text">查询分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#explain"><span class="nav-number">11.1.</span> <span class="nav-text">explain()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#hint"><span class="nav-number">11.2.</span> <span class="nav-text">hint()</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#原子操作常用命令"><span class="nav-number">12.</span> <span class="nav-text">原子操作常用命令</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MongoDB-Java"><span class="nav-number">13.</span> <span class="nav-text">MongoDB Java</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Chao</span>
</div>



<div class="theme-info">
  <span class="post-count">博客全站共118.7k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">访客总量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  









  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/three/three.min.js"></script>

  
  <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.2"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.2"></script>


  

  

</body>
</html>
